package org.laobai.shop.mgt.controller;

import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.laobai.shop.goods.entity.Brand;
import org.laobai.shop.goods.service.BrandService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;

@Controller
@RequestMapping("brand")
public class BrandController {

    @DubboReference
    private BrandService brandService;

    @RequestMapping("list/{cp}/{ps}")
    public String list(@PathVariable(name = "cp") int cp, @PathVariable(name = "ps") int ps,
                       @RequestParam(required = false) Brand brand, Model model){
        PageInfo<Brand> page = brandService.page(cp, ps, brand);
        model.addAttribute("page",page);
        return "/brand/list";
    }

    @RequestMapping("toAdd")
    public String toAdd(){
        return "/brand/add";
    }

//    @RequestMapping("save")
//    public String save(Brand brand, MultipartFile file){
//        String path = "D:/test/imgs";
//        /*
//         1、文件是否上传
//         2、为文件重命名
//            a、获取文件原始名
//            b、获取后缀名
//            c、UUID、时间戳设置文件名
//         3、判断文件是否存在
//         4、保存文件
//         5、为实体类赋值
//         */
//        // 文件是否上传 3.3.3.4.png
//        if(Objects.nonNull(file)){
//            String originalFilename = file.getOriginalFilename();
//            String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
//            String newName = System.currentTimeMillis()+extendName;
//
//
//            File parent = new File(path);
//            if(!parent.exists()){
//                parent.mkdirs();
//            }
//
//
//            try {
//                file.transferTo(new File(parent,newName));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            brand.setPic(newName);
//        }
//
//        brandService.save(brand);
//        return "redirect:list/1/5";
//    }
    @RequestMapping("save")
    public String save(Brand brand, MultipartFile file, HttpServletResponse response) throws IOException {
        // 判断图片不为空
        String pic = Base64.getEncoder().encodeToString(file.getBytes());
        brand.setPic(pic);
        brandService.save(brand);
        return "redirect:list/1/5";
    }

}
